import os
from fastapi import Request, HTTPException
from starlette.responses import Response
from starlette.middleware.base import BaseHTTPMiddleware
import jwt
from starlette.status import HTTP_401_UNAUTHORIZED
from dotenv import load_dotenv
from routes.admin_white_list import no_token
from services.auth_handler import AuthHandler
from config.logging import logger

class JwtMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, excluded_paths=None):
        super().__init__(app)
        load_dotenv()
        self.secret_key = os.getenv('SECRET_KEY')
        self.excluded_paths = excluded_paths or no_token

    async def dispatch(self, request: Request, call_next):
        if not any(request.url.path.startswith(path) for path in self.excluded_paths):
            token = request.headers.get("Authorization")
            if token is None or not token.startswith("Bearer "):
                return Response(content="Not authenticated", status_code=HTTP_401_UNAUTHORIZED)

            try:
                token_data = token.split(" ")[1]
                payload = AuthHandler().decode_token(token_data)
                print(f"token--{token_data}-------{payload}---------")
                if payload is None:
                    return Response(content="Invalid token -payload None", status_code=HTTP_401_UNAUTHORIZED)
                request.state.user = payload  # 在这里设置 user
            except jwt.PyJWTError:
                return Response(content="Invalid token", status_code=HTTP_401_UNAUTHORIZED)

        response = await call_next(request)
        return response
# class JwtMiddleware(BaseHTTPMiddleware):
#     def __init__(self, app, excluded_paths=None):
#         super().__init__(app)
#         load_dotenv()
#         self.secret_key = os.getenv('SECRET_KEY')
#         self.excluded_paths = excluded_paths or no_token
#
#     async def dispatch(self, request: Request, call_next):
#         if request.url.path not in self.excluded_paths:
#             token = request.headers.get("Authorization")
#             if token is None or not token.startswith("Bearer "):
#                 return Response(content="Not authenticated", status_code=HTTP_401_UNAUTHORIZED)
#
#             try:
#                 token_data = token.split(" ")[1]
#                 `logger.info(f"token信息{token_data}")`
#                 payload = AuthHandler().decode_token(token_data)
#                 print(f"token--{token_data}-------{payload}---------")
#                 if payload is None:
#                     return Response(content="Invalid token", status_code=HTTP_401_UNAUTHORIZED)
#                 request.state.user = payload  # 在这里设置 user
#             except jwt.PyJWTError:
#                 return Response(content="Invalid token", status_code=HTTP_401_UNAUTHORIZED)
#
#         response = await call_next(request)
#         return response
